<template>
<!-- 分配座位弹框 -->
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="close" :close-on-click-modal="false" width="60%">
    <el-form inline id="allotSeat">
      <el-form-item label="placeX:(横排)">
        <el-input-number v-model="placeX" :min="1" :max="99" label="描述文字" @change="loadSeats()"></el-input-number>
      </el-form-item>
      <el-form-item label="placeY:(竖列)">
        <el-input-number v-model="placeY" :min="1" :max="99" label="描述文字" @change="loadSeats()"></el-input-number>
      </el-form-item> 
      <el-form-item label="可用:">
        <img src="../../assets/white.png">
      </el-form-item> 
      <el-form-item label="不可用:">
        <img src="../../assets/red.png">
      </el-form-item> 
      <div v-if="this.seats.length!==0">分配了{{placeX*placeY}}个座位</div>
      <div v-else>暂未分配座位</div>
    </el-form>
     <span slot="footer" class="dialog-footer">
        <el-button @click="close()" :loading="buttonLoading">取 消</el-button>
        <el-button type="primary" @click="add()" :loading="buttonLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import white from 'assets/white.png'
import red from 'assets/red.png'
export default {
 data() {
    return {
      dialogVisible: false,
      buttonLoading: false,
      loading: false,
      title: "分配座位",
      placeX:1,
      placeY:1, 
      seats:[],
      result:[]
    };
  },
  props:{
    curId: {},
  },
  watch:{
    dialogVisible(val){
      if(val){
        console.log(this.curId,333333)
        if (this.curId) {
          this.getDetail(this.curId);
        }
      }
    },
    seats: {
      handler(val) {
        if(val){
          this.clickSeat();
        } 
      },
    },
  },
  methods:{
    //打开
    open() {
      this.dialogVisible = true;
    },
    //关闭
    close() {
      this.dialogVisible = false;
      this.placeX = ''
      this.placeY = ''
      this.delseats()
      this.seats = ''
      this.result = ''
    },
    //详情
    getDetail(_id){
      console.log(_id,77)
      this.loading = true;
      this.$http.get("seats/findByRoom/" + _id)
        .then((res) => {
          console.log(res,456)
          if(res.status === 200 & res.data.data.length!==0){
            this.seats = res.data.data
            console.log(this.seats,1234)
            //过滤数组中status为2的对象，并遍历提取出每一项的place
            this.result =  this.seats.filter(item => item.status === 2).map(item => item.place)
            console.log(...this.result,2222);
            //取数组中最后一项的place，拆分出X、Y
            this.placeX = this.seats.slice(-1)[0].place.split(',')[0]
            this.placeY = this.seats.slice(-1)[0].place.split(',')[1]
            this.loadSeats();
            this.loading = false;
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error("获取座位信息失败！")
        })
    },
    //新增
    add() { 
      if(this.seats.length===0){
        this.$message.error("请先分配座位再确定！")
        return
      }
      this.$confirm('确认生成此座位表吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
         this.buttonLoading = true;    
         console.log(this.seats,"提交")
         //return
         this.$http.post("seats/addSeats/" + this.curId,this.seats)
         .then((res) => {
           console.log(res)
           if(res.status === 200){
             this.close();
             this.$message.success("分配成功!");
             this.$emit("getListData");
           }     
           this.buttonLoading = false;
         })
         .catch((err) => { 
           this.buttonLoading = false;
           this.$message.error("分配失败")
         });
      })
      .catch(()=>{

      })
    },
    //监听点击座位并改变数组
    clickSeat(){
      //限制点击事件为seatslog.img中
      var articleView = document.querySelector("#seatslog")
      let check = articleView.getElementsByTagName("img");
      console.log(check,555)
      console.log(this.seats,999)
      let arr = this.seats
      for (let i = 0, len = check.length; i < len; i++) {
        //查询数组中place对应id,并将status转为2,颜色变红
        check[i].onclick=function(){
          let obj = arr.find(o => o.place === this.id);
          if(this.src == red){
            this.src = white
            obj.status = 1
          }else if(this.src == white){
            this.src = red
            obj.status = 2      
          }
          console.log(obj,94616351681)
          console.log(this.id,5555)
         }    
       }
    },
    //删除seats表格，防止多次生成表
    delseats(){  
      var element = document.getElementById("seatslog");
      if(element)
      //删除需先切换到父级
      element.parentNode.removeChild(element);
    },
    //渲染座位并赋ID
    loadSeats(){
        //重置数组对象
        this.seats = []
        this.delseats()
        console.log(this.result)
        let arr = this.result
        //row:横向个数、col:纵向个数、size:图片大小,gap:图片间距
        var row=this.placeY,col=this.placeX,size=50,gap=5;
        var wrap=document.createElement("div");
        wrap.style.margin="0 auto";
        wrap.id = "seatslog";
        wrap.style.width=(size+gap)*col+"px";
        wrap.style.height=(size+gap)*row+"px";
        for(var i=0;i<row;i++){
            var rows=document.createElement("div");
            rows.style.float="left";
            rows.style.marginBottom=gap+"px";
            for(var j=0;j<col;j++){
                var div=document.createElement("img");                 
                div.style.width=size+"px";
                div.style.height=size+"px";
                div.style.float="left";
                div.style.marginLeft=gap+"px";
                div.id = `${i+1},${j+1}`;
                //判断当前div是否为result中的一个值,若不是，则返回-1
                if(arr.indexOf(`${div.id}`)!== -1){
                  div.src=red
                  status = 2
                }else{
                  div.src=white
                  status = 1
                }
                //生成seats数组
                rows.appendChild(div); 
                const  obj = {
                 roomId: this.curId,
                 place: div.id ,
                 status: parseInt(status),
                 seatKey: this.curId + div.id
                }
                this.seats.push(obj)
            }
            wrap.appendChild(rows);
        }  
        document.getElementById('allotSeat').appendChild(wrap);
    }
  },
};
</script>

<style lang="scss" scoped>
</style>